<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .exform {
            margin: 100px auto;
            width: 450px;
            height: auto;
            border: 2px solid mediumspringgreen;
            padding: 30px;
            background-color: lightgoldenrodyellow;
            border-radius: 8px;
        }

        textarea {
            width: 350px;
            height: 120px;
            resize: none;
        }

        .exform li {
            line-height: 25px;
            margin-left: 55px;
            width: 350px;
            background-color: papayawhip;
        }

        ul li a {
            float: right;
            text-decoration: none;
            color: gray;
            /* 标签内字体颜色 */
        }
    </style>
</head>

<body>
    <!-- JS -->
    <!-- HTML -->
    <div class="exform">
        <p align="center">评论发布</p>
        <p align="center">
            <textarea id="text"></textarea>
            <button id="btn">发布</button>
        </p>
        <ul id="ul"></ul>
    </div>
    
    <script>
        onload = function () {
            var btn = document.getElementById("btn");
            var ul = document.getElementById("ul");
            btn.onclick = function () {
                var text = document.getElementById("text");
                var neirong = text.value;
                // 创建新节点 li
                var newLi = document.createElement('li');
                if (neirong.length == 0) { alert("请输入内容！！") }
                else {
                    newLi.innerHTML = neirong + "<a href='javascript:;'>删除</a>";// 点击后阻止跳转
                    // 将创建好的 li 作为 ul 的子节点
                    if (ul.children.length != 0) {
                        // 如果已有评论，将最后发布的评论放在第一条
                        ul.insertBefore(newLi, ul.children[0]);
                    }
                    else {
                        // 如果当前没有评论则直接添加子节点
                        ul.appendChild(newLi);
                    }
                }
                // 清空发送框
                text.value = "";

                var pinglun = document.getElementsByTagName("a");
                for (var i = 0; i < pinglun.length; i++) {
                    pinglun[i].onclick = function () {
                        ul.removeChild(this.parentNode);   //删除ul中的li
                    }
                }
            }
        }
    </script>


</body>

</html>